/*
 * Created on Sep 29, 2006
 */
package com.scalar.chiptrack.operations.distributor.actions;

import java.util.HashMap;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.operations.distributor.dao.DistributorDao;
import com.scalar.chiptrack.operations.distributor.forms.DistributorInventoryForm;
import com.scalar.chiptrack.operations.distributor.DistributorInventory;
import com.scalar.chiptrack.operations.process.dao.FinishedGoodsDAO;
import com.scalar.chiptrack.operations.packingslip.actions.SearchPackingSlipAction;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.NewCustomerDAO;
import com.scalar.chiptrack.users.User;

/**
 * @author ravi
 */
public class DistributorInventoryAction  extends ChipTrackAction
{
	public ActionForward execute (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		HttpSession session = request.getSession();
		User user 			= (User) session.getAttribute ( SessionKeys.USER_KEY );
		HashMap<String,String> errors 		= new HashMap<String,String>();
		HashMap<String,String> info 		= new HashMap<String,String>();

        String action 		    = request.getParameter( "action" );
		String productId 	    = request.getParameter( "productId" );
		String distributorId 	= request.getParameter( "distributorId" );
        String lineItemNo       = request.getParameter( "lineItemNo" );
        String distSalesOrderId = request.getParameter( "distSalesOrderId" );
        DistributorInventory pulledInventory        = null;
        DistributorInventory dbInventory            = null;
        ArrayList pulledLotsList                    = null;
        ArrayList dbLotsList                        = null;
        HashMap   lineItemsWithPulledLotDetailsMap  = null;
        String actionForward = "success";
        if ( user == null )
		{
			session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, "/distributorSalesSearch.do?" + request.getQueryString() );
			return ( mapping.findForward( "login" ) );
		}

        if( request.getAttribute( SessionKeys.INFO_MESSAGES ) != null )
		{
			info.putAll( ( HashMap ) request.getAttribute( SessionKeys.INFO_MESSAGES ) );
		}
		if( request.getAttribute( SessionKeys.ERROR_MESSAGES ) != null )
		{
			errors.putAll( ( HashMap ) request.getAttribute( SessionKeys.ERROR_MESSAGES ) );
		}
		
		if ( action == null ){ 	action = ""; }

        DistributorInventoryForm inventoryForm = (DistributorInventoryForm) form;

        if( productId != null && productId.trim().length() > 0 )
        {
            try
            {
                inventoryForm.setProduct_Id( Integer.parseInt( productId.trim() ) );
            }
            catch( NumberFormatException nfe ) {}
        }

        if( distributorId != null && distributorId.trim().length() > 0 )
        {
            try
            {
                inventoryForm.setDistributorId( Integer.parseInt( distributorId.trim() ) );
            }
            catch( NumberFormatException nfe ) {}
        }

        if( lineItemNo != null && lineItemNo.trim().length() > 0 )
        {
            try
            {
                inventoryForm.setLineItemNo ( Integer.parseInt( lineItemNo.trim() ) );
            }
            catch( NumberFormatException nfe ) {}
        }

        //System.out.println("------------------Dist-Inv-Action-- action = " + action + "  productId = " + productId + " distributorId = " + distributorId );

        if( "search".equalsIgnoreCase( action ) )
        {
            request.setAttribute( "controlIndex", request.getParameter("controlIndex") );
            int distributorSalesOrderId= -1;
            try
                {
                   distributorSalesOrderId= Integer.parseInt(distSalesOrderId.trim());
                }
                catch(Exception e)
                {
                    System.out.println("e = " + e);
                    distributorSalesOrderId= -1;

                }

            //int modifyStatus= Integer.parseInt(request.getParameter("modifyStatus"));
            try
            {                   
                inventoryForm.setInventoryList( DistributorDao.loadDistributorInventory( inventoryForm.getProduct_Id(),inventoryForm.getDistributorId(),  distributorSalesOrderId, "DISTRIBUTORSALES" ) );

                lineItemsWithPulledLotDetailsMap = ( HashMap ) session.getAttribute("lineItemWithPulledLotDetails");
                
                if( lineItemsWithPulledLotDetailsMap != null && lineItemsWithPulledLotDetailsMap.isEmpty() == false )
                {
                    pulledLotsList  = ( ArrayList ) lineItemsWithPulledLotDetailsMap.get( inventoryForm.getLineItemNo() + "" );
                    dbLotsList      = inventoryForm.getInventoryList();

                    if( pulledLotsList != null && pulledLotsList.isEmpty() == false )
                    {
                        for( int i = 0; i < pulledLotsList.size(); i++ )
                        {
                            pulledInventory = ( DistributorInventory ) pulledLotsList.get( i );

                            for( int j = 0; j < dbLotsList.size(); j++ )
                            {
                                dbInventory = ( DistributorInventory ) dbLotsList.get( j );
                                
                                if ( dbInventory.getLot_number().equalsIgnoreCase( pulledInventory.getLot_number() )
                                        && dbInventory.getCsLitId()==pulledInventory.getCsLitId() )
                                {
                                    dbInventory.setQty_pulled( pulledInventory.getQty_pulled() );
                                    dbInventory.setQty_available( dbInventory.getQty_available() );
                                }
                            }
                        }
                    }
                } 

                inventoryForm.setDistributor( CustomerDAO.getCustomerName( null, inventoryForm.getDistributorId() ) );
                inventoryForm.setPartNumber( FinishedGoodsDAO.getPartNumberByProductId( null, inventoryForm.getProduct_Id() ) );

                if( inventoryForm.getInventoryList() == null || inventoryForm.getInventoryList().size() == 0 )
                {
                    errors.put( "No Inventory Available at the Distributor", "" );
                }
            }
            catch( Exception e )
            {
                e.printStackTrace();
                errors.put( "Could not retrive Inventory details ", null );
            }

        }
        //this for Edit and scrap the distributor Inv
        else if ("editsearch".equalsIgnoreCase(action) )
        {
            actionForward = "edit";

            ArrayList<DistributorInventory> inventoryList = DistributorDao.loadDistributorInventory(inventoryForm.getProduct_Id(),inventoryForm.getDistributorId(),-1, "INVENTORY");

            inventoryForm.setInventoryList( inventoryList);
            request.setAttribute( "distributorList", NewCustomerDAO.getAllDistributorNamesByUserType( null, user, true ) );
		    request.setAttribute( "partNumbersList", SearchPackingSlipAction.loadManufacturingProducts () );
        }
        else if ("adjustInventory".equalsIgnoreCase(action ) )
        {
              actionForward = "edit";
              DistributorDao.adjustDistributorInventory( null, inventoryForm );
              info.put("Successfully adjusted the distributor Inventory", null);
              inventoryForm.setInventoryList( null);
              inventoryForm.setDistributorId(0);
              inventoryForm.setProduct_Id(0);
              request.setAttribute( "distributorList", NewCustomerDAO.getAllDistributorNamesByUserType( null, user, true ) );
		      request.setAttribute( "partNumbersList", SearchPackingSlipAction.loadManufacturingProducts () );
        }
        /*if( "modifySearch".equalsIgnoreCase( action ) )
        {
            request.setAttribute( "controlIndex", request.getParameter("controlIndex") );
            int distSalesOrderId= 0;
            try
                {
                     distSalesOrderId = Integer.parseInt(request.getParameter("distSalesOrderId"));
                }
                catch(NumberFormatException e)
                {
                    distSalesOrderId= 0;
                }
            try
            {

                inventoryForm.setInventoryList( DistributorDao.loadDistributorInventory (inventoryForm.getDistributorId(), inventoryForm.getProduct_Id(), distSalesOrderId) );

                lineItemsWithPulledLotDetailsMap = ( HashMap ) session.getAttribute("lineItemWithPulledLotDetails");

                if( lineItemsWithPulledLotDetailsMap != null && lineItemsWithPulledLotDetailsMap.isEmpty() == false )
                {
                    pulledLotsList  = ( ArrayList ) lineItemsWithPulledLotDetailsMap.get( inventoryForm.getLineItemNo() + "" );
                    dbLotsList      = inventoryForm.getInventoryList();

                    if ( pulledLotsList != null && pulledLotsList.isEmpty() == false )
                    {
                        for ( int i = 0; i < pulledLotsList.size(); i++ )
                        {
                            pulledInventory = ( DistributorInventory ) pulledLotsList.get( i );

                            for( int j = 0; j < dbLotsList.size(); j++ )
                            {
                                dbInventory = ( DistributorInventory ) dbLotsList.get( j );

                                if ( dbInventory.getLot_number().equalsIgnoreCase( pulledInventory.getLot_number() ) )
                                {
                                    dbInventory.setQty_pulled( pulledInventory.getQty_pulled() );
                                    dbInventory.setQty_available(dbInventory.getQty_available() + pulledInventory.getQty_pulled());
                                }
                            }
                        }
                    }
                }

                inventoryForm.setDistributor( CustomerDAO.getCustomerName( null, inventoryForm.getDistributorId() ) );
                inventoryForm.setPartNumber( FinishedGoodsDAO.getPartNumberByProductId( null, inventoryForm.getProduct_Id() ) );

                if( inventoryForm.getInventoryList() == null || inventoryForm.getInventoryList().size() == 0 )
                {
                    errors.put( "No Inventory Available at the Distributor", "" );
                }
            }
            catch( Exception e )
            {
                e.printStackTrace();
                errors.put( "Could not retrive Inventory details ", null );
            }

        }*/
        else if( "save".equalsIgnoreCase( action ) )
        {
            request.setAttribute( "controlIndex", request.getParameter("controlIndex") );
            request.setAttribute( "totalQtyPulled", request.getParameter("totalQtyPulled") );

            try
            {
                lineItemsWithPulledLotDetailsMap = ( HashMap ) session.getAttribute("lineItemWithPulledLotDetails");

                if( ( lineItemsWithPulledLotDetailsMap == null ) || ( lineItemsWithPulledLotDetailsMap.isEmpty() ) )
                {
                    lineItemsWithPulledLotDetailsMap = new HashMap();
                }
                lineItemsWithPulledLotDetailsMap.put ( inventoryForm.getLineItemNo() + "", inventoryForm.getInventoryList() );

                session.setAttribute( "lineItemWithPulledLotDetails", lineItemsWithPulledLotDetailsMap );
                request.setAttribute( "closeWindowAfterSave", "true" );
            }
            catch( Exception e )
            {
                e.printStackTrace();
                errors.put ( "Could not save Inventory details ", null );
            }
        }

        request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
        request.setAttribute( SessionKeys.INFO_MESSAGES, info );
		return( mapping.findForward( actionForward ) );
	}	

}
